/**
 * 物料安全库存设置界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Goods.SafetyInventoryEditForm", {
  extend: "PSI.AFX.Form.EditForm",

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;
    const entity = me.getEntity();

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 620,
      height: 400,
      layout: "border",
      items: [{
        region: "center",
        border: 0,
        bodyPadding: 10,
        layout: "fit",
        items: [me.getGoodsGrid()]
      }, {
        region: "north",
        border: 0,
        layout: {
          type: "table",
          columns: 2
        },
        height: 40,
        bodyPadding: 10,
        items: [{
          xtype: "hidden",
          id: me.buildId(me, "hiddenId"),
          name: "id",
          value: entity.get("id")
        }, {
          fieldLabel: "物料",
          labelWidth: 40,
          labelAlign: "right",
          labelSeparator: "",
          xtype: "displayfield",
          value: "<span class='PSI-field-note'>" + entity.get("code") + " "
            + entity.get("name") + " "
            + entity.get("spec") + "</span>"
        }]
      }],
      buttons: [{
        text: "保存",
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-button-ok",
        handler: me._onOK,
        scope: me,
        id: "buttonSave"
      }, {
        text: "取消",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.confirm("请确认是否取消当前操作？",
            () => {
              me.close();
            });
        },
        scope: me,
        id: "buttonCancel"
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.editHiddenId = PCL.getCmp(me.buildId(me, "hiddenId"));
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    const el = me.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Goods/siInfo"),
      params: {
        id: me.editHiddenId.getValue()
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);

          const store = me.getGoodsGrid().getStore();
          store.removeAll();
          store.add(data);

          me._cellEditing.startEdit(0, 2);
        } else {
          me.showInfo("网络错误")
        }
      }
    });
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    PCL.getBody().mask("正在保存中...");
    me.ajax({
      url: me.URL("SLN0001/Goods/editSafetyInventory"),
      params: {
        jsonStr: me.getSaveData()
      },
      callback(options, success, response) {
        PCL.getBody().unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            me.tip("成功保存数据", true);
            me.close();
            me.getParentForm()._onGoodsSelect.apply(me.getParentForm());
          } else {
            me.showInfo(data.msg);
          }
        }
      }
    });
  },

  /**
   * @private
   */
  getGoodsGrid() {
    const me = this;
    if (me._goodsGrid) {
      return me._goodsGrid;
    }

    const modelName = me.buildModelName(me, "GoodsSafetyInventory");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["warehouseId", "warehouseCode", "warehouseName",
        "safetyInventory", "unitName", "inventoryUpper"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._cellEditing = PCL.create("PSI.UX.CellEditing", {
      clicksToEdit: 1,
      listeners: {
        edit: {
          fn: me.cellEditingAfterEdit,
          scope: me
        }
      }
    });

    me._goodsGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-EF",
      viewConfig: {
        enableTextSelection: true
      },
      plugins: [me._cellEditing],
      columnLines: true,
      columns: [{
        header: "仓库编码",
        dataIndex: "warehouseCode",
        width: 100,
        menuDisabled: true,
        sortable: false
      }, {
        header: "仓库名称",
        dataIndex: "warehouseName",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "库存上限",
        dataIndex: "inventoryUpper",
        width: 120,
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        format: "0",
        editor: {
          xtype: "numberfield",
          allowDecimals: false,
          hideTrigger: true
        }
      }, {
        header: "安全库存量",
        dataIndex: "safetyInventory",
        width: 120,
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        format: "0",
        editor: {
          xtype: "numberfield",
          allowDecimals: false,
          hideTrigger: true
        }
      }, {
        header: "计量单位",
        dataIndex: "unitName",
        width: 80,
        menuDisabled: true,
        sortable: false
      }],
      store: store
    });

    return me._goodsGrid;
  },

  /**
   * @private
   */
  cellEditingAfterEdit(editor, e) {
    // do nothing
  },

  /**
   * @private
   */
  getSaveData() {
    const me = this;

    const result = {
      id: me.editHiddenId.getValue(),
      items: []
    };

    const store = me.getGoodsGrid().getStore();
    for (let i = 0; i < store.getCount(); i++) {
      const item = store.getAt(i);
      result.items.push({
        warehouseId: item.get("warehouseId"),
        invUpper: item.get("inventoryUpper"),
        si: item.get("safetyInventory")
      });
    }

    return me.encodeJSON(result);
  }
});
